import React, { useState, useEffect, useRef } from 'react';
import TjTable from '@/pages/ETrade/components/TjTable';
import { Button, Form, message, Modal, Tabs } from 'antd';
import { baseNumberColumns, mediumAndLongColumns, tabList } from './helper';
import { TjContent, TjModal, TjModalTitle, TjUpload } from '@/tjComponents';
import {
  deleteStationBaseConfigData,
  downLoadSxMediumAndLong,
  editSxMediumAndLongData,
  queryStationBaseConfigData,
  querySxMediumAndLongData,
  sxUploadUrl,
  updateStationBaseConfigData,
} from '../../service';
import { HttpCode } from '#/utils/contacts.js';
import _ from 'lodash';
import moment, { isMoment } from 'moment';
import { useForm } from 'antd/es/form/Form';
import { ExclamationCircleOutlined, UploadOutlined } from '@ant-design/icons';
import SxSdModalContent from '../SxSdModalContent';
import type { TreeDatatype } from '@/hooks/useRequestPowerAfterInit';

import './index.less';
import { EditTabelRowStyle } from '../../helper';

const { confirm } = Modal;
const SxConfig: React.FC<ISxConfigProps> = (props) => {
  const [activeKey, setActiveKey] = useState<string>(props.defaultActiveKey);
  const [baseNumberData, setBaseNumberData] = useState<any[]>([]);
  const [mediumAndLongData, setMediumAndLongData] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const isEdit = useRef<boolean>(false);
  const [form] = useForm();

  const changeLoading = (status: boolean) => {
    props.changeGlobalLoading && props.changeGlobalLoading(status);
    setLoading(status);
  };

  const onTabChange = (key: string) => {
    setActiveKey(key);
    props.onTabChange && props.onTabChange(key);
  };

  const getMediumAndLong = () => {
    const year = _.get(props.filterValues, 'year', undefined);
    if (year && isMoment(year)) {
      const params = {
        year: year.format('YYYY'),
        quarter: year.quarter(),
        marketId: props.marketId,
      };
      isEdit.current = false;

      changeLoading(true);
      querySxMediumAndLongData(params)
        .then((res: any) => {
          if (res.statusCode === HttpCode.SUCCESS) {
            const list = res.data.dataList || [];

            if (list.length > 0) {
              const lastRow = {
                timeOrder: '算数平均值',
                referencePrice: res.data.arithmeticMeanReferencePrice || '',
                lowerLimitPrice: res.data.arithmeticMeanLowerLimitPrice || '',
                upperLimitPrice: res.data.arithmeticMeanUpperLimitPrice || '',
                isLast: true,
              };
              list.push(lastRow);
            }
            setMediumAndLongData(list);
          } else {
            message.warning(res.message);
            setMediumAndLongData([]);
          }
        })
        .finally(() => {
          changeLoading(false);
        });
    }
  };

  const getBaseNumberData = () => {
    changeLoading(true);
    const years = _.get(props.filterValues, 'year', []);
    const stationIdList = _.get(props.filterValues, 'stationIdList', []);
    const obj = {
      startYear: moment(years[0]).format('YYYY'),
      endYear: moment(years[1]).format('YYYY'),
      stationIdList,
      marketId: props.marketId,
      menuCode: props.menuCode,
    };
    queryStationBaseConfigData(obj)
      .then((res) => {
        if (res.statusCode === HttpCode.SUCCESS) {
          const stations = _.get(props.currentProvinceInfo, 'stations', []);
          if (res.data && res.data.length > 0 && stations.length > 0) {
            const formValues: any = {};
            res.data.forEach((v: any) => {
              v.stationName = stations.find(
                (s: any) => v.stationIdList[0] === s.stationId,
              ).stationName;
              formValues[`list@${v.id}`] = [];
              if (v.list) {
                v.list.forEach((item: any) => {
                  if (item.baseFlag) {
                    formValues[`list@${v.id}`].push(item.month);
                  }
                });
              }
            });
            form.setFieldsValue(formValues);
            setBaseNumberData(res.data);
          } else {
            setBaseNumberData([]);
          }
        }
      })
      .finally(() => {
        changeLoading(false);
      });
  };

  const query = () => {
    if (activeKey === '1') {
      getMediumAndLong();
    }
    if (activeKey === '2') {
      getBaseNumberData();
    }
  };

  // 基数
  const saveBaseNumberData = (id: number, index: number) => {
    const value: any = form.getFieldValue([`list@${id}`]) || [];
    const newRow: any = baseNumberData[index];
    newRow.list.forEach((v: any) => {
      if (value.indexOf(v.month) > -1) {
        v.baseFlag = true;
      } else {
        v.baseFlag = false;
      }
    });
    newRow.menuCode = props.menuCode;
    changeLoading(true);
    updateStationBaseConfigData(newRow)
      .then((res) => {
        if (res.statusCode === HttpCode.SUCCESS) {
          message.success('修改成功');
          query();
        } else {
          message.error(res.message);
        }
      })
      .finally(() => {
        changeLoading(false);
      });
  };
  const cancelBaseNumberData = (id: number, index: number) => {
    const newBaseNumberData = [...baseNumberData];
    delete newBaseNumberData[index].isEdit;
    setBaseNumberData(newBaseNumberData);
  };
  const editBaseNumberData = (id: number, index: number) => {
    const newBaseNumberData = [...baseNumberData];
    newBaseNumberData[index].isEdit = true;
    setBaseNumberData(newBaseNumberData);
  };
  const delBaseNumberData = (id: number, index: number) => {
    confirm({
      title: '是否确认删除',
      icon: <ExclamationCircleOutlined />,
      onOk: () => {
        deleteStationBaseConfigData({
          idList: [id],
        }).then((res) => {
          if (res.statusCode === HttpCode.SUCCESS) {
            message.success('删除成功');
            query();
          } else {
            message.error(res.message);
          }
        });
      },
    });
  };
  const sxAdd = () => {
    const stations = _.get(props.currentProvinceInfo, 'stations', []);
    const initValue: any = {
      year: moment(),
    };
    initValue.stationIdList = stations.map((v: any) => v.stationId);
    TjModal.open({
      title: <TjModalTitle title="新增" />,
      content: (
        <SxSdModalContent
          treeData={props.treeData}
          marketId={props.marketId}
          initValue={initValue}
        />
      ),
      onOk: (values) => {
        const months = _.range(1, 13);
        const params: any = {
          marketId: props.marketId,
          year: moment(values.year).format('YYYY'),
          menuCode: props.menuCode,
          list: [],
          stationIdList: values.stationIdList,
          strategyType: props.strategyType,
        };

        months.forEach((v: number) => {
          params.list.push({
            month: v,
            baseFlag: values.list && values.list.includes(v) ? true : false,
          });
        });
        return updateStationBaseConfigData(params)
          .then((res) => {
            if (res.statusCode === HttpCode.SUCCESS) {
              message.success('新增成功');
              query();
            } else {
              message.error(res.message);
            }
          })
          .finally(() => {
            changeLoading(false);
          });
      },
    });
  };

  // 中长期
  const mediumAndLongSave = (id: number, index: number) => {
    form.validateFields().then((values: any) => {
      const year = _.get(props.filterValues, 'year', undefined);

      const data: any = {
        timeOrder: mediumAndLongData[index].timeOrder,
        id,
        year: year.format('YYYY'),
        quarter: year.quarter(),
        marketId: props.marketId,
      };
      for (const key in values) {
        const [k, id] = key.split('@');
        data[k] = values[key];
      }
      changeLoading(true);
      editSxMediumAndLongData(data)
        .then((res: any) => {
          if (res.statusCode === HttpCode.SUCCESS) {
            message.success('修改成功');
            isEdit.current = false;
            query();
          } else {
            message.warning(res.message);
            changeLoading(false);
          }
        })
        .catch(() => {
          changeLoading(false);
        });
    });
  };
  const mediumAndLongCancel = (id: number, index: number) => {
    const newDataSource = [...mediumAndLongData];
    newDataSource[index].isEdit = false;
    isEdit.current = false;
    setMediumAndLongData(newDataSource);
  };
  const mediumAndLongEdit = (id: number, index: number) => {
    if (isEdit.current) {
      return message.warning('只能同时编辑一条数据');
    }
    const newDataSource = [...mediumAndLongData];
    newDataSource[index].isEdit = true;
    const formData: any = {};
    const keys: string[] = ['referencePrice', 'lowerLimitPrice', 'upperLimitPrice'];
    keys.forEach((k) => {
      const name = `${k}@${id}`;
      formData[name] = newDataSource[index][k];
    });
    isEdit.current = true;
    setMediumAndLongData(newDataSource);
    form.setFieldsValue(formData);
  };

  const downLoad = () => {
    const year = _.get(props.filterValues, 'year', undefined);
    if (year) {
      const params = {
        year: year.format('YYYY'),
        quarter: year.quarter(),
        marketId: props.marketId,
      };
      downLoadSxMediumAndLong(params).then((res: any) => {
        if (res.statusCode === HttpCode.SUCCESS) {
          const blob = new Blob([res.file]);
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = '中长期限价.xlsx'; // 设置下载文件的名称
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          window.URL.revokeObjectURL(url);
        } else {
          message.error(res.message);
        }
      });
    }
  };

  useEffect(() => {
    if (props.filterValues && Object.keys(props.filterValues).length > 0) {
      query();
    }
  }, [props.filterValues]);

  return (
    <div className="sx-config">
      <TjContent>
        <Tabs
          activeKey={activeKey}
          onChange={onTabChange}
          tabBarExtraContent={{
            right: (
              <div>
                {activeKey === '1' ? (
                  <div className="tab-right">
                    <TjUpload
                      accept=".xls,.xlsx"
                      uploadUrl={sxUploadUrl}
                      loading={loading}
                      uploadOtherParams={{ marketId: props.marketId }}
                      uploadSuccessCb={() => query()}
                    />
                    <Button
                      type="link"
                      icon={<UploadOutlined />}
                      loading={loading}
                      onClick={downLoad}
                      disabled={mediumAndLongData.length === 0}
                    >
                      导出
                    </Button>
                  </div>
                ) : (
                  <>
                    <Button type="link" onClick={sxAdd}>
                      新增
                    </Button>
                  </>
                )}
              </div>
            ),
          }}
        >
          {tabList.map((v) => {
            return <Tabs.TabPane tab={v.tab} key={v.key} />;
          })}
        </Tabs>

        <Form form={form} className="table-box">
          <TjTable
            isLoading={loading}
            components={{ Cell: EditTabelRowStyle }}
            columns={
              activeKey === '1'
                ? mediumAndLongColumns(mediumAndLongSave, mediumAndLongCancel, mediumAndLongEdit)
                : baseNumberColumns(
                    saveBaseNumberData,
                    cancelBaseNumberData,
                    editBaseNumberData,
                    delBaseNumberData,
                  )
            }
            dataSource={activeKey === '1' ? mediumAndLongData : baseNumberData}
          />
        </Form>
      </TjContent>
    </div>
  );
};

interface ISxConfigProps {
  defaultActiveKey: string;
  onTabChange?: (key: string) => void;
  filterValues: any;
  marketId: string;
  marketName?: string;
  currentProvinceInfo?: any;
  menuCode?: string;
  treeData: TreeDatatype[];
  strategyType?: string;
  changeGlobalLoading?: (loading: boolean) => void;
}

export default SxConfig;
